var config = require('../../config.js')
var http = require('../..//utils/httpHelper.js')
var util = require('../../utils/util.js')
Page({
  data: {
    userInfo:{},
    allGoods:{},
    sumPrice:0,
    address:''
  },
  onLoad: function () {
    var that = this;
    let userInfo = wx.getStorageSync('user');
    that.setData({userInfo:userInfo});
  },
  onShow:function (){
    var allGoods =  wx.getStorageSync('shoppingcar');
    var sumPrice = 0;
    for(var i=0;i< allGoods.length;i++){
      var price = allGoods[i].price;
      var count =  allGoods[i].buycount;
      price = util.accMul(price,count);
      if (allGoods[i].discount&&allGoods[i].discount>0) {
        var discount =  allGoods[i].discount;
        price = util.accMul(price,discount);
      }
      allGoods[i].pay = price;
      sumPrice = util.accAdd(sumPrice,price);
    }
    this.setData({ allGoods:allGoods, sumPrice:sumPrice });
    this.getDefaultAddress();
  },
  toAddress:function(){
    wx.navigateTo({url: '/pages/address/index'})
  },
  getDefaultAddress:function(){
    //获取地址
    var that = this;
    var data = {userId:this.data.userInfo.userId};
    http.httpGet(config.clubApi.getAddressList,data,function(res){
      if(res.code == '200'){
        var allAddress = res.data;
        var address = '';
        for(var i=0;i<allAddress.length;i++){
          if( allAddress[i].isfirst == 1){
            address = allAddress[i];
            break;
          }
        }
        if(address == '' && allAddress.length > 0){
          address = allAddress[0];
        }
        that.setData({address:address});
      }
    });
  },
  createOrder:function(buyGoods,callback){    
    http.httpPut(config.clubApi.createOrder,buyGoods,function(res){
      if (res.code == '200') {
        //订单创建成功
        typeof callback == "function" && callback(res)
      }else {
        //订单创建失败
        typeof callback == "function" && callback('')
      }
    })
  },
  settlement:function (){
    var that = this;
    //检查地址是否为空
    if(this.data.address == ""){
      wx.showModal({
        title: '提示',
        content: '请您先添加邮寄地址！',
        success: function(res) {
          if (res.confirm) {
            that.toAddress();
          }
          return;
        }
      })
    }
    //继续生成订单
    var addressid = this.data.address.id;
    var allGoods = this.data.allGoods;
    var userId = this.data.userInfo.userId;
    var buyGoods = [];
    allGoods.forEach(function(goods){
      var amount = util.accMul(goods.price,goods.buycount);
      var data = {
        appId: config.APPID,
        shopId:goods.shopId,
        productId:goods.id,
        amount:amount,
        discount:goods.discount,
        payAmount:goods.pay,
        num:goods.buycount,
        addressId:addressid,
        createBy:userId
      };
      buyGoods.push(data);
    })
    this.createOrder(buyGoods,function(res){
      if (res.code == '200') {
        try {
          let params = res.data;
          WeixinJSBridge.invoke(
            "getBrandWCPayRequest",
            params,
            function (res) {
              if (res.err_msg == "get_brand_wcpay_request:ok") {
                wx.showToast({
                  title: '支付成功',
                  icon: 'none',
                  duration: 3000
                });
              } else {
                wx.showToast({
                  title: '支付失败',
                  icon: 'none',
                  duration: 3000
                });
              }
              wx.setStorageSync('shoppingcar', []);
              wx.navigateBack();
            }
          );
        }catch (f) {
          if (res.msg) {
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 2000
            });
          }
          wx.setStorageSync('shoppingcar', []);
          wx.navigateBack({delta:2});
        }
      }
    });
  }
})